
import { resetRouter } from '@/router'
import { login } from '../../api/user'
import { getToken, setToken, removeToken, getUser, setUser, removeUser } from '@/utils/auth'
import { Message } from 'element-ui'

// userRole：1-管理员，2-普通用户，3-临时用户（专家用户为临时用户）
// roleType: 1-专家用户，2-专家小组长，3-专家大组长

const getDefaultState = () => {
  let user = new Object()
  if (getUser() !== undefined) {
    user = JSON.parse(getUser())
  } else {
    user.userRole = 0
    user.loginName = ''
    user.userId = 0
    user.roleType = 0
  }

  return {
    token: getToken(),
    userRole: user.userRole,
    loginName: user.loginName,
    userId: user.userId,
    roleType: user.roleType
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_NAME: (state, loginName) => {
    state.loginName = loginName
  },
  SET_ROLE: (state, userRole) => {
    state.userRole = userRole
  },
  SET_ROLE_TYPE: (state, roleType) => {
    state.roleType = roleType
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { loginName, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ loginName: loginName.trim(), password: password }).then(response => {
        if (response.indexOf("200") != -1) {
          const token = response.split(",")[1]
          const { loginName, userRole, userId, roleType } = JSON.parse(window.atob(token))
          commit('SET_TOKEN', token)
          commit('SET_USER_ID', userId)
          commit('SET_NAME', loginName)
          commit('SET_ROLE', userRole)
          commit('SET_ROLE_TYPE', roleType)
          setToken(token)
          setUser({ userRole, loginName, userId, roleType })
          resolve()
        } else {
          Message({
            type: 'error',
            message: response.split(",")[1],
            showClose: true
          })
          reject(response.split(",")[1])
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  logout({ commit }) {
    removeToken()
    removeUser()
    resetRouter()
    commit('RESET_STATE')
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      removeUser()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

